package com.bocai.dahuatech.ui.frag;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;

import com.bocai.dahuatech.Bean.BaseBean;
import com.bocai.dahuatech.Bean.HomeBannerBean;
import com.bocai.dahuatech.Bean.NewProductBean;
import com.bocai.dahuatech.R;
import com.bocai.dahuatech.base.BaseFragment;
import com.bocai.dahuatech.ui.activity.LoginActivity;
import com.bocai.dahuatech.ui.activity.NewProductDetailActivity;
import com.bocai.dahuatech.ui.activity.NewProductListActivity;
import com.bocai.dahuatech.ui.activity.NewsListActivity;
import com.bocai.dahuatech.ui.activity.PointsListActivity;
import com.bocai.dahuatech.ui.activity.SolutionListActivity;
import com.bocai.dahuatech.ui.adapter.HomeNewProductAdapter;
import com.bocai.dahuatech.ui.view.AutoScrollViewPager;
import com.bocai.dahuatech.ui.view.LoopViewPager;
import com.bocai.dahuatech.ui.view.MyListView;
import com.bocai.dahuatech.utils.AESUtils;
import com.bocai.dahuatech.utils.DialogUtil;
import com.bocai.dahuatech.utils.RZUtil;
import com.bocai.dahuatech.utils.SharePrefencesUtil;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * 首页主界面
 */
public class Fragment_Home extends BaseFragment implements View.OnClickListener,AdapterView.OnItemClickListener
{
    private View view;
    @Bind(R.id.mlv_home_newproduct)
    MyListView mlvNewProduct;
    @Bind(R.id.ll_home_solution)
    LinearLayout llSolution;
    @Bind(R.id.ll_home_news)
    LinearLayout llNews;
    @Bind(R.id.ll_home_points)
    LinearLayout llPoints;
    @Bind(R.id.vp_home)
    AutoScrollViewPager vp_home;
    @Bind(R.id.swipe_home)
    SwipeRefreshLayout swipe;
    @Bind(R.id.ll_home_newproduct)
    LinearLayout llNewProduct;
    private BannerAdapter mBannerAdapter;
    private View dot1;
    private View dot2;
    private View dot3;
    private View dot4;
    private View dot5;
    private View dot6;
    private View dot7;
    private List<View> dots; // 图片标题正文的那些点
    private HomeBannerBean homeBannerbean;
    NewProductBean newProductBean;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        view = inflater.inflate(R.layout.homefrag, container, false);
        initView();
        return view;
    }

    private void initView()
    {
        DisplayMetrics dm=new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width=dm.widthPixels;
        int height=width/2;
        ButterKnife.bind(this, view);
        ViewGroup.LayoutParams params=vp_home.getLayoutParams();
        params.width=width;
        params.height=height;
        vp_home.setLayoutParams(params );
        getBanner();
        dot1 = view.findViewById(R.id.v_dot1);
        dot2 = view.findViewById(R.id.v_dot2);
        dot3 = view.findViewById(R.id.v_dot3);
        dot4 = view.findViewById(R.id.v_dot4);
        dot5 = view.findViewById(R.id.v_dot5);
        dot6 = view.findViewById(R.id.v_dot6);
        dot7 = view.findViewById(R.id.v_dot7);
        dots = new ArrayList<>();
        dots.add(dot1);
        dots.add(dot2);
        dots.add(dot3);
        dots.add(dot4);
        dots.add(dot5);
        dots.add(dot6);
        dots.add(dot7);
        mlvNewProduct.setFocusable(false);
        initEvent();


    }

    public void getNewProducts(){
        getTestApi().getThreeNewProduct()
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(newProductObserver);
    }

    Observer<BaseBean> newProductObserver=new Observer<BaseBean>() {
        @Override
        public void onCompleted()
        {

        }

        @Override
        public void onError(Throwable e)
        {
            hideLoading();
            swipe.setRefreshing(false);
            Log.e("error",e.toString());
            showToast(R.string.neterror);
        }

        @Override
        public void onNext(BaseBean baseBean)
        {
            hideLoading();
            swipe.setRefreshing(false);
            if(baseBean.getReturnNo().equals("1"))
            {
                String result=AESUtils.decode(baseBean.getContent());
                result=start+result+end;
                Log.e("result",result);
                newProductBean=new Gson().fromJson(result,NewProductBean.class);
                mlvNewProduct.setAdapter(new HomeNewProductAdapter(getActivity(),newProductBean));

            }
            else
            {
                showToast(baseBean.getReturnInfo());
            }
        }
    };
    private void getBanner() {
       String code= SharePrefencesUtil.getCustomerCode(getActivity());
        Log.e("code",code);
        getTestApi().getHomeBanner(SharePrefencesUtil.getCustomerCode(getActivity()))
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }
    Observer<BaseBean> observer=new Observer<BaseBean>() {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            getNewProducts();
        }

        @Override
        public void onNext(BaseBean baseBean) {
            getNewProducts();
            if(baseBean.getReturnNo().equals("1"))
            {
                String result= AESUtils.decode(baseBean.getContent());
                result=start+result+end;
                Log.e("result",result);
                homeBannerbean=new Gson().fromJson(result,HomeBannerBean.class);
                if(homeBannerbean.getContent().size()==2){
                    dot2.setVisibility(View.VISIBLE);
                    dot3.setVisibility(View.GONE);
                    dot4.setVisibility(View.GONE);
                    dot5.setVisibility(View.GONE);
                    dot6.setVisibility(View.GONE);
                }
                if(homeBannerbean.getContent().size()==3){
                    dot2.setVisibility(View.VISIBLE);
                    dot3.setVisibility(View.VISIBLE);
                    dot4.setVisibility(View.GONE);
                    dot5.setVisibility(View.GONE);
                    dot6.setVisibility(View.GONE);
                }
                if(homeBannerbean.getContent().size()==4){
                    dot2.setVisibility(View.VISIBLE);
                    dot3.setVisibility(View.VISIBLE);
                    dot4.setVisibility(View.VISIBLE);
                    dot5.setVisibility(View.GONE);
                    dot6.setVisibility(View.GONE);
                }
                if(homeBannerbean.getContent().size()==5){
                    dot2.setVisibility(View.VISIBLE);
                    dot3.setVisibility(View.VISIBLE);
                    dot4.setVisibility(View.VISIBLE);
                    dot5.setVisibility(View.VISIBLE);
                    dot6.setVisibility(View.GONE);
                }
                if(homeBannerbean.getContent().size()==6){
                    dot2.setVisibility(View.VISIBLE);
                    dot3.setVisibility(View.VISIBLE);
                    dot4.setVisibility(View.VISIBLE);
                    dot5.setVisibility(View.VISIBLE);
                    dot6.setVisibility(View.VISIBLE);
                }
                startBanner();
            }
        }
    };
    private void startBanner()
    {
        //广告banner
        mBannerAdapter=new BannerAdapter(getFragmentManager());
        vp_home.setOnPageChangeListener(new MyPageChangeListener());
        vp_home.setAdapter(mBannerAdapter);
        vp_home.startAutoScroll();
        vp_home.setInterval(5000);
    }
    private void initEvent()
    {
        llNewProduct.setOnClickListener(this);
        llSolution.setOnClickListener(this);
        llNews.setOnClickListener(this);
        llPoints.setOnClickListener(this);
        mlvNewProduct.setOnItemClickListener(this);
        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                showLoading();
                getBanner();
            }
        });
    }

    @Override
    public void onDestroyView()
    {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
    @Override
    public void onResume()
    {
        super.onResume();
    }


    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {

            case R.id.ll_home_newproduct:
                startActivity(new Intent(getActivity(), NewProductListActivity.class));
                break;
            case R.id.ll_home_solution:
                startActivity(new Intent(getActivity(), SolutionListActivity.class));
                break;
            case R.id.ll_home_news:
                startActivity(new Intent(getActivity(), NewsListActivity.class));
                break;
            case R.id.ll_home_points:
                if(SharePrefencesUtil.getFAccessFlag(getActivity())==0)//游客 去登录
                {
                    {
                        DialogUtil.dialogForTwoButton(getActivity(), R.string.nologin, R.string.know, R.string.tologin, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(getActivity(), LoginActivity.class);
                                intent.putExtra("tologin", false);
                                startActivity(intent);
                                DialogUtil.dismissTowDialog();
                            }
                        });
                    }
                }
                else if(SharePrefencesUtil.getFAccessFlag(getActivity())!=2) //个人  去认证
                {

                    DialogUtil.dialogForTwoButton(getActivity(), R.string.notseepointshop, R.string.know, R.string.toauthentication, new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            if(SharePrefencesUtil.getFAccessFlag(getActivity())==6)
                            {
                                DialogUtil.dismissTowDialog();
                                DialogUtil.dialogForOneButton(getActivity(),R.string.alreadysubmitdata,R.string.know);
                            }else  if(SharePrefencesUtil.getFAccessFlag(getActivity())==7)
                            {
                                RZUtil.renZheng(getActivity());
//                                Intent intent1=new Intent(getActivity(),RegistDistributorSecendActivity.class);
//                                IndividualBean bean=new IndividualBean();
//                                intent1.putExtra("register",bean);
//                                intent1.putExtra("what", "certifiled");
//                                startActivity(intent1);
                                DialogUtil.dismissTowDialog();
                            }
                        }
                    });
                }else{
                    startActivity(new Intent(getActivity(), PointsListActivity.class));
                }
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(getActivity(), NewProductDetailActivity.class);
        intent.putExtra("productId", newProductBean.getContent().get(position).getFPROD_ID());
        intent.putExtra("solutionId","0");
        startActivity(intent);
    }



    private class MyPageChangeListener implements LoopViewPager.OnPageChangeListener
    {

        private int oldPosition = 0;

        @Override
        public void onPageScrollStateChanged(int arg0)
        {

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2)
        {

        }

        @Override
        public void onPageSelected(int position)
        {
            position = (homeBannerbean.getContent().size() + position%homeBannerbean.getContent().size())%homeBannerbean.getContent().size();
            dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal);
            dots.get(position).setBackgroundResource(R.drawable.dot_focused2);
            oldPosition = position;
        }
    }
    class BannerAdapter extends FragmentPagerAdapter
    {

        public BannerAdapter(FragmentManager fm)
        {
            super(fm);
        }

        @Override
        public Fragment getItem(int position)
        {
            position = (homeBannerbean.getContent().size()+ position%homeBannerbean.getContent().size())%homeBannerbean.getContent().size();
            BannerFrag fragment = new BannerFrag();
            fragment.getData(homeBannerbean.getContent().get(position));
            return fragment;
        }

        @Override
        public CharSequence getPageTitle(int position)
        {
            return "";
        }

        @Override
        public int getCount()
        {
            return homeBannerbean.getContent().size();
        }
    }
}
